package com.gitee.kenewstar.springbootstorage.disk;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Objects;

/**
 * @author kenewstar
 */
@Slf4j
@RestController
@RequestMapping("/object")
public class ObjectController {

    @Resource
    private ObjectDiskProps objectDiskProps;


    @GetMapping("/{objectName}")
    public ResponseEntity<Object> getObject(@PathVariable String objectName) {
        StringBuilder returnInfo = new StringBuilder();
        String path = objectDiskProps.getRoot() + File.separator + objectName;
        log.info("access file ==> {}", path);
        // 读取文件内容
        try(FileInputStream fis = new FileInputStream(path)) {
            // 转换成文本信息
            byte[] data = new byte[1024];
            int readCount;
            while ((readCount = fis.read(data)) != -1) {
                returnInfo.append(new String(data,0,readCount));
            }
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(returnInfo);
    }

    @PutMapping("/{objectName}")
    public ResponseEntity<Object> putObject(@PathVariable String objectName, @RequestBody String objectData) {
        String path = objectDiskProps.getRoot() + File.separator + objectName;
        log.info("access file ==> {}", path);
        this.ifDirCreate(objectDiskProps.getRoot());

        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
        try (FileWriter fileWriter = new FileWriter(path)) {
            fileWriter.append(objectData);
            fileWriter.flush();
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
        return ResponseEntity.ok("创建成功");
    }

    private void ifDirCreate(String path){
        try {
            File dir = new File(path);
            if (dir.isDirectory() && !dir.exists()) {
                dir.createNewFile();
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }


}
